package com.inspur.edp.bef.bizentity.json.increment;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.inspur.edp.bef.bizentity.common.BizEntityJsonConst;
import com.inspur.edp.bef.bizentity.exceptions.BusinessEntityErrorCodeEnum;
import com.inspur.edp.bef.bizentity.exceptions.BusinessEntityException;
import com.inspur.edp.bef.bizentity.increment.BizEntityIncrement;
import com.inspur.edp.bef.bizentity.increment.entity.action.MgrActionIncrement;
import com.inspur.edp.cef.designtime.api.json.CefNames;
import com.inspur.edp.das.commonmodel.entity.increment.CommonModelIncrement;
import com.inspur.edp.das.commonmodel.json.increment.CommonModelIncrementDeserializer;
import com.inspur.edp.das.commonmodel.json.increment.CommonObjectIncrementDeserializer;

import java.io.IOException;

public class BizEntityIncrementDeserializer extends CommonModelIncrementDeserializer {
    @Override
    protected CommonObjectIncrementDeserializer getObjectIncrementDeserializer() {
        return new BizObjectIncrementDeserializer();
    }

    @Override
    protected void readExtendInfo(CommonModelIncrement value, JsonNode node) {
        BizEntityIncrement increment = (BizEntityIncrement)value;
        JsonNode actionIncrements = node.get(BizEntityJsonConst.BizMgrActions);
        if(actionIncrements != null)
            readActions(increment, actionIncrements);
    }

    private void readActions(BizEntityIncrement increment, JsonNode node){
        ArrayNode array = trans2Array(node);
        for (JsonNode childNode : array){
            MgrActionIncrementDeserializer serializer = new MgrActionIncrementDeserializer();
            ObjectMapper mapper = new ObjectMapper();
            SimpleModule module = new SimpleModule();
            module.addDeserializer(MgrActionIncrement.class, serializer);
            mapper.registerModule(module);
            try {
                String key = childNode.get(CefNames.Id).textValue();
                JsonNode valueNode = childNode.get(BizEntityJsonConst.BizMgrAction);

                MgrActionIncrement voActionIncrement = mapper.readValue(mapper.writeValueAsString(valueNode), MgrActionIncrement.class);
                voActionIncrement.setActionId(key);
                increment.getActions().put(key, voActionIncrement);
            }  catch (IOException e) {
                throw BusinessEntityException.createException(BusinessEntityErrorCodeEnum.GSP_BEMODEL_JSON_0001, e, "VoActionIncrement");
            }
        }
    }

    protected CommonModelIncrement createCommonModelIncrement() {
        return new BizEntityIncrement();
    }
}
